# Create your views here.
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.shortcuts import render_to_response,HttpResponse
from django.http import HttpResponseRedirect,Http404
from django.template import RequestContext,Context,loader
from Ebidding.auction.models import *
from django.contrib.auth import logout
import datetime
from Ebidding.search import get_query
def items_detail(request,Id):
	requested_items=get_object_or_404(Item,Id=Id)
	try:
	    item_author=user_details.objects.get(UserId=requested_items.Owner)
	except user_details.DoesNotExist:
	    item_author=False
	has_bid=True
	try:
		item_bid=WinningBid.objects.get(ItemId=Id)
	except WinningBid.DoesNotExist:
		has_bid=False
	tags=[]
	for tag in requested_items.Tags.all():
		tags.append(tag)
	#time calculation
	now=datetime.datetime.now()
	expire_time=requested_items.date + datetime.timedelta(15,0,0)
	rem_time=expire_time-now
	timer={}
	timer['days']=rem_time.days
	timer['hours']=rem_time.seconds/3600
	timer['minutes']=(rem_time.seconds-timer['hours']*3600)/60
	
	if has_bid:
		context={
			'items':requested_items,
			'tag':tags,
			'item_bid':item_bid,
			'has_bid':has_bid,
			'item_author':item_author,
			'rem_time':timer,
			}
	else:
		context={
			'items':requested_items,
			'tag':tags,
			'has_bid':has_bid,
			'item_author':item_author,
			'rem_time':timer,
			}
	
	return render_to_response(
		'itemsdetail.html',
		context,
		context_instance=RequestContext(request),
		)
def main_page(request):
  item=Item.objects.order_by('-date')
  todaydate=datetime.datetime.now()
  
  variables=RequestContext(request,{'item':item,'todaydate':todaydate,'users':request.user,
  })
  return render_to_response(

    'main_page.html', variables
  )
def search(request):
    query_string = ''
    found_entries = None
    if ('q' in request.POST) and request.POST['q'].strip():
        query_string = request.POST['q']
    
        entry_query = get_query(query_string, ['Name', 'Description',])

        found_entries = Item.objects.filter(entry_query)#.order_by('date')

    return render_to_response('search/search_result.html',
                          { 'query_string': query_string, 'found_entries': found_entries },
                          context_instance=RequestContext(request))
